<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px; margin-bottom: 20px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加图片
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="序号" prop="id" align="center" width="60">
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" align="center" width="120">
        <template slot-scope="{ row }">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column label="内容" prop="content" align="center" width="180">
        <template slot-scope="{ row }">
          <span class="item-content">{{ row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" prop="image" align="center" width="240">
        <template slot-scope="{ row }">
          <img :src="row.image" alt="" width="160" height="80">
        </template>
      </el-table-column>

      <el-table-column label="排序" prop="sort" align="center" width="60">
        <template slot-scope="{ row }">
          <span>{{ row.sort }}</span>
        </template>
      </el-table-column>

      <el-table-column label="展示位" prop="type" align="center" width="100">
        <template slot-scope="{ row }">

          <span>{{ row.type_name }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="更新时间"
        prop="updateTime"
        align="center"
        width="155"
      >
        <template slot-scope="{ row }">
          <span>{{ row.update_time }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        align="center"
        width="155"
      >
        <template slot-scope="{ row }">
          <span>{{ row.create_time }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item>
          <el-upload
            action="image/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :accept="'image/*'"
          >
            <img width="100%" :src="temp.image" alt="">
            <el-button class="filter-item" type="primary" size="medium">
              上传图片
            </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="标题">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="跳转链接">
          <el-input v-model="temp.link" />
        </el-form-item>
        <el-form-item label="排序值">
          <el-input v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            v-model="temp.content"
            :autosize="{ minRows: 1, maxRows: 4 }"
            type="textarea"
            placeholder="内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createBanner, deleteBanner } from '@/api/banner'
import { parseTime } from '@/utils'

export default {
  name: 'Index',
  components: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      listLoading: true,
      downloadLoading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        content: '',
        startTime: new Date(),
        endTime: new Date(),
        title: '',
        sort: 1,
        type: 1,
        status: 1,
        link: '',
        image: ''
      },
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        startTime: [
          {
            type: 'date',
            required: true,
            message: 'startTime is required',
            trigger: 'change'
          }
        ],
        endTime: [
          {
            type: 'date',
            required: true,
            message: 'endTime is required',
            trigger: 'change'
          }
        ],
        image: [
          {
            required: true,
            message: 'imgUrl is required',
            trigger: 'blur'
          }
        ],
        title: [
          {
            required: true,
            message: 'title is required',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList().then((response) => {
        this.list = response.data.list
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      })
    },

    handleUploadSuccess(response, file, fileList) {
      this.temp.image = response.data
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.startTime = parseTime(this.temp.startTime)
          this.temp.endTime = parseTime(this.temp.endTime)
          createBanner(this.temp).then((response) => {
            if (response.code === 0) {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: response.message
              })
            }
          })
        }
      })
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp.id = row.id
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.createData()
        }
      })
    },

    deleteData(param) {
      deleteBanner(param).then((response) => {
        if (response.code === 0) {
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
      })
    },

    handleDelete(row) {
      const data = {
        id: row.id
      }
      this.$confirm('此操作将会删除这条记录，是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteData(data)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        remark: '',
        startTime: new Date(),
        endTime: new Date(),
        title: '',
        content: '',
        sort: 1,
        type: 1,
        status: 1,
        link: '',
        image: ''
      }
    }
  }
}
</script>

<style lang="scss">
.item-content {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>
